﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Profile;
using NUnit.Framework;
using COFE.Core;

namespace COFE.Data.Profile
{
    public class DBUserProfileManager : IUserProfileManager2
    {
        #region Constructor

        public DBUserProfileManager()
        {
            if (!DBUserProfile.Exists(COFE.Core.Profile.AdminUserProfile.AdminUserName))
                DBUserProfile.Create(COFE.Core.Profile.AdminUserProfile.AdminUserName, 
                    Guid.NewGuid().ToString());

            AdminUserProfile = new AdminUserProfile();
            CurrentUserProfile = new UnauthorizedUserProfile();            
        }

        #endregion

        #region Methods

        public void SetCurrentUserProfile(IUserProfile userProfile)
        {
            if (userProfile is DBUserProfile || 
                userProfile is UnauthorizedUserProfile ||
                userProfile == COFEShared.AdminUserProfile || 
                userProfile == null)
            {
                CurrentUserProfile = userProfile;
                CurrentUserProfileChanged(this, EventArgs.Empty);
            }
            else throw new ArgumentException("This userprofile is not supported.");
        }

        public IUserProfile2 CreateUser(string userName, string password)
        {
            return DBUserProfile.Create(userName, password);
        }

        public void DeleteUser(string userName)
        {
            DBUserProfile.Delete(userName);
        }

        public IUserProfile2 GetUserProfile(string userName, string password)
        {
            return DBUserProfile.GetUserProfile(userName, password);
        }

        public IUserProfile2 GetUserProfile(Guid authorizationKey)
        {
            return DBUserProfile.GetUserProfile(authorizationKey);
        }

        public void Logout(Guid authorizationKey)
        {
            DBUserProfile.Logout(authorizationKey);
        }
        

        #endregion

        #region Data

        [ThreadStatic]
        private static IUserProfile _currentUserProfile;

        #endregion

        #region Public Properties        
        public IUserProfile AdminUserProfile { get; private set; }
        public IUserProfile CurrentUserProfile { get { return _currentUserProfile; } private set { _currentUserProfile = value; } }
        public event EventHandler CurrentUserProfileChanged = (o, e) => { };

        public IEnumerable<IUserProfile2> Users
        {
            get { return DBUserProfile.GetAllUserProfiles(); }
        }

       

        #endregion




       
    }
}
